//
//  MyOauthViewController.swift
//  weibo08
//
//  Created by 陈杰明 on 16/2/28.
//  Copyright © 2016年 JM. All rights reserved.
//

import UIKit
import SVProgressHUD

class MyOauthViewController: UIViewController, UIWebViewDelegate {

    override func loadView() {
        
        self.view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置背景
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
        
        webView.delegate = self
        //加载页面
        let url = MyNetWorkTool.sharedInstance.oauthLogin()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }

    func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
    }
    //填充
    func autoFill() {
     
        //执行js代码
        let js = "document.getElementById('userId').value='jiemchan@163.com';document.getElementById('passwd').value='cjm667445.'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Black)
    }
    //加在完毕
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //取消
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
        if error?.code != 102{
        SVProgressHUD.showErrorWithStatus("加载失败", maskType: SVProgressHUDMaskType.Black)
        }
//        print("error:\(error)")
        
    }
    //询问是否去加载某个请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString
        print("weburl:\(urlString)")
        //点击取消：http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        //点击授权：http://www.baidu.com/?code=d3bc0cf559231523e352a7cb1447ec5f
        
        if urlString!.hasPrefix(MyNetWorkTool.sharedInstance.redirect_uri) {
        
            //query是？后面的请求
            let query = request.URL?.query
            let codeStr = "code="
            if query!.hasPrefix(codeStr){
                let queryNS = query! as NSString
                let code = queryNS.substringFromIndex(codeStr.characters.count)
                
                //模型相关的操作不放到控制器里，放到ViewModel
                MyUserAccountViewModel.sharedInstance.loadAccessToken(code, loadAccessTokenCallBack: { (error) -> () in
                    //判断错误
                    if error != nil {
                
                        SVProgressHUD.showErrorWithStatus("网络不给力")
                        //延迟
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            //关闭控制器
                            self.close()
                        })
                        return
                    }
                    //账户保存成功关闭
                    self.close()
                    //跳转到welcomeVieController
                    AppDelegate.outSwitchRootViewCOntroller(false)
                })
                
            }else{
                //点击按钮关闭控制器
                close()
            }
            
            return false
            
        }else {
        
            
        }
        
       return true 
        
    }
    //MARK: - 懒加载
    lazy var webView = UIWebView()
}
